import path from "path"
import fs from "fs";
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';


dotenv.config({
  path:[
    path.resolve(process.cwd(), '.env.${process.env.NODE_ENV}'),
    path.resolve(process.cwd(), '.env'),
  ]
});

const app = express();

app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

//前端接口
import indexRoutes from './routes/index/index.js';
app.use('/api/v1/index', indexRoutes);

//后端接口
//app.use(`/api/v1/admin`, routes);

//处理上述路由不存在的其他地址
app.use(function(req,res,next){
  //res.type("json");
  res.send({
    code:404,
    msg:`"${req.path}"地址不存在`
  })
});

app.use(function(err,req,res,next){
  console.log(err);
  let logPath = path.resolve(process.cwd(),`./logs/${new Date().getTime()}.log`);
  fs.writeFileSync(logPath,err.toString())
  res.send({
    code:500,
    msg:"服务器运行错误，请联系管理员"
  })
});
const PORT = process.env.PORT ?? 8000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

export default app;
